/**
 * router部分逻辑抽出（简化逻辑）
 */
import { getRouter } from '@/api/router'
import Layout from '@/layout'
import store from '@/store'

export async function handleRouter(router) {
  let resList = store.state.router.menuList
  let routerList = []
  // 判断是否获取过路由如果获取过就不再获取
  if ($chy.isEmpty(resList)) {
    routerList = await new Promise((resolve, reject) => {
      getRouter().then(res => {
        // resList = res.data.children
        resList = handleMenuList(res.data.children)
        // 获取到的路由放到vuex里
        store.commit('router/addMenuList', resList)
        resolve(handleRouterList(resList))
      }).catch(err => {
        reject(err)
      })
    })
  } else {
    routerList = handleRouterList(resList)
  }
  // console.log('routerList', routerList)
  router.addRoute(
    {
      path: '/',
      name: 'layout',
      redirect: '/index',
      component: Layout,
      children: routerList,
      meta: {
        title: 'layout',
        noNeedLogin: true,
        icon: ''
      }
    }
  )
}

/**
 * 处理路由列表，返回处理后的路由列表
 * @param {*} resList 
 * @returns 
 */
function handleRouterList(resList) {
  let resultList = []
  resList.forEach(ele => {
    if (!$chy.isEmpty(ele.children)) {
      resultList.push(...handleRouterList(ele.children))
    } else {
      resultList.push({
        path: ele.path,
        name: ele.name,
        hidden: ele.hidden,
        meta: ele.meta,
        children: ele.children,
        component: (resolve) => require([`@/views/${ele.component}`], resolve)
      })
    }
  })
  return resultList
}
/**
 * 处理菜单列表，返回菜单
 * @param {*} resList 
 * @param {*} parentPath 
 * @returns 
 */
function handleMenuList(resList, parentPath) {
  return resList.map(ele => {
    return {
      path: !$chy.isEmpty(parentPath) ? `/${parentPath}/${ele.path}` : `/${ele.path}`,
      name: ele.name,
      hidden: ele.hidden,
      meta: {
        sort: ele.sort,
        ...ele.meta
      },
      children: !$chy.isEmpty(ele.children) ? handleMenuList(ele.children, ele.path) : ele.children,
      component: ele.component
    }
  })
}